import random
import numpy as np

class Network(object):
    def __init__(self, sizes):
    	self.num_layers = len(sizes)
    	self.sizes = sizes
	self.biases = [np.random.randn(y,1) for y in sizes[1:]]
	self.weights = [np.random.randn(y,x) for x,y in zip(sizes[:-1], sizes[1:])]
    
    def feedforward(self,a):
	for b,w in zip(self.biases, self.weights):
	    a = sigmoid(np.dot(w,a) + b)
	return a

    def SGD(self,training_data, epochs, mini_batch_size, eta, test_data=None):
    	"""Train the neural network using mini-batch stochastic
    	   gradient descent.  The ``training_data`` is a list of tuples
    	   ``(x, y)`` representing the training inputs and the desired
    	   outputs.  The other non-optional parameters are
    	   self-explanatory.  If ``test_data`` is provided then the
    	   network will be evaluated against the test data after each
    	   epoch, and partial progress printed out.  This is useful for
    	   tracking progress, but slows things down substantially."""

	if test_data:
	    n_test = len(test_data)

	n = len(training_data)
	for j in xrange(epochs):
	    random.shuffle(training_data)
	    mini_batches = [
	        training_data[k:k+mini_batch_size] 
	        for k in xrange(0,n,mini_batch_size)]

	    for mini_batch in mini_batches:
	        self.update_mini_batch(mini_batch, eta)
	    if test_data:
	        print "Epoch {0}: {1} / {2}".format(j,self.evaluate(test_data), n_test)
	    else:
	        print "Epoch {0} complete".format(j)

    def forward(self,x,y):
      	  #feedforward
      	  activation = x
      	  activations = [x]
      	  zs = [x]
	  for b, w in zip(self.biases,self.weights):
	      z = np.dot(w, activation) + b
	      activation = sigmoid(z)
	      zs.append(z)
	      activations.append(activation)
	  return (zs, activations)

    def backward(self,x,y, zs, activations):
      	  L = self.num_layers 
      	  # L layer
      	  delta_b = [np.zeros(b.shape) for b in self.biases]
      	  delta_w = [np.zeros(w.shape) for w in self.weights]
      	  delta = self.cost_derivative(activations[L-1],y)*sigmoid_prime(zs[L-1])
	  for L in xrange(self.num_layers-1,0,-1):
	      delta_b[L-1] = delta
	      delta_w[L-1] = np.dot(delta, activations[L-1].transpose())
	      delta = np.dot(self.weights[L-1].transpose(),delta) * sigmoid_prime(zs[L-1])
	  return (delta_b,delta_w)

      
    def backprop(self, x, y):
      	  nabla_b = [np.zeros(b.shape) for b in self.biases]
      	  nabla_w = [np.zeros(w.shape) for w in self.weights]
      	  #feedforward
      	  (zs, activations) = self.forward(x,y)
	  #backward
	  return self.backward(x, y, zs, activations)
    
    def evaluate(self, test_data):
        """Return the number of test inputs for which the neural
        network outputs the correct result. Note that the neural
        network's output is assumed to be the index of whichever
        neuron in the final layer has the highest activation."""
        test_results = [(np.argmax(self.feedforward(x)), y)
                        for (x, y) in test_data]
        return sum(int(x == y) for (x, y) in test_results)

    def cost_derivative(self, output_activations, y):
        """Return the vector of partial derivatives \partial C_x /
        \partial a for the output activations."""
        return (output_activations-y)
    
    def update_mini_batch(self, mini_batch, eta):
        """Update the network's weights and biases by applying
        gradient descent using backpropagation to a single mini batch.
        The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta``
        is the learning rate."""
        nabla_b = [np.zeros(b.shape) for b in self.biases]
        nabla_w = [np.zeros(w.shape) for w in self.weights]
        for x, y in mini_batch:
            delta_nabla_b, delta_nabla_w = self.backprop(x, y)
            nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
            nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
        self.weights = [w-(eta/len(mini_batch))*nw
                        for w, nw in zip(self.weights, nabla_w)]
        self.biases = [b-(eta/len(mini_batch))*nb
                       for b, nb in zip(self.biases, nabla_b)]


def sigmoid(z):
    """The sigmoid function."""
    return 1.0/(1.0+np.exp(-z))

def sigmoid_prime(z):
    """Derivative of the sigmoid function."""
    return sigmoid(z)*(1-sigmoid(z))




if __name__ == "__main__":
    import mnist_loader
    training_data, validation_data, test_data = mnist_loader.load_data_wrapper()
    net = Network([784, 30, 10])
    net.SGD(training_data, 30, 10, 3.0, test_data=test_data)




	    





    
